using MediatR;
using Microsoft.EntityFrameworkCore;
using RBAC.Domain.SmartHealthcare.Hosiptial;
using RBAC.ErrorCode;
using RBAC.Interstructrue;
using SmartHealthcare.Read.Api.Application.Command.Medicine;
using SmartHealthcare.Read.Api.DTo;

namespace SmartHealthcare.Read.Api.Application.Handler.Medicine
{
    /// <summary>
    /// 药物智能搜索处理器
    /// </summary>
    public class SearchMedicineHandler : IRequestHandler<SearchMedicineCommand, APIResult<List<MedicineSearchDto>>>
    {
        private readonly RBACDbContext _dbContext;
        private readonly ILogger<SearchMedicineHandler> _logger;

        public SearchMedicineHandler(RBACDbContext dbContext, ILogger<SearchMedicineHandler> logger)
        {
            _dbContext = dbContext;
            _logger = logger;
        }

        /// <summary>
        /// 药物智能搜索
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<List<MedicineSearchDto>>> Handle(SearchMedicineCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<List<MedicineSearchDto>>();

            try
            {
                // 检查是否有搜索参数
                if (!request.HasSearchParameters())
                {
                    _logger.LogInformation("未提供搜索参数，将查询所有药物信息");
                }
                else
                {
                    _logger.LogInformation($"开始药物智能搜索，药物名称：{request.MedicineName}，药物编码：{request.MedicineCode}，药物类型：{request.MedicineType}，生产厂家：{request.Manufacturer}，状态：{request.Status}");
                }

                // 构建查询
                var query = _dbContext.medicines.AsQueryable();

                // 根据参数筛选
                if (!string.IsNullOrWhiteSpace(request.MedicineName))
                {
                    query = query.Where(x => x.MedicineName.Contains(request.MedicineName));
                    _logger.LogInformation($"按药物名称筛选：{request.MedicineName}");
                }

               

                if (!string.IsNullOrWhiteSpace(request.MedicineType))
                {
                    // 使用DrugType作为药物类型进行搜索
                    query = query.Where(x => x.DrugType == request.MedicineType);
                    _logger.LogInformation($"按药物类型筛选：{request.MedicineType}");
                }

               

                if (request.Status.HasValue)
                {
                    // 使用IsDeleted作为状态进行搜索（0:正常 1:停用）
                    query = query.Where(x => x.IsDeleted == (request.Status.Value == 0));
                    _logger.LogInformation($"按状态筛选：{request.Status.Value}");
                }

                // 只查询未删除的药物
                query = query.Where(x => x.IsDeleted == false);

                // 获取所有符合条件的药物（不分页）
                var medicines = await query.ToListAsync(cancellationToken);

                // 转换为DTO
                var resultList = medicines.Select(medicine => new MedicineSearchDto
                {
                    Id = medicine.Id,
                    MedicineName = medicine.MedicineName ?? string.Empty,
                  
                    Specification = medicine.Specification ?? string.Empty,
                    MedicineType = medicine.DrugType ?? string.Empty, // 使用DrugType作为药物类型
         
                    UnitPrice = medicine.Price, // 使用Price作为单价
                    StockQuantity = medicine.Inventory, // 使用Inventory作为库存数量

                    ExpiryDate = medicine.EffectiveDate, // 使用EffectiveDate作为有效期
                    Description = medicine.Effect ?? string.Empty, // 使用Effect作为描述
                    Indications = medicine.Effect ?? string.Empty, // 使用Effect作为适应症
                    Usage = string.Empty, // 暂时为空，可以后续添加
                    Precautions = string.Empty, // 暂时为空，可以后续添加
                    Contraindications = string.Empty, // 暂时为空，可以后续添加
                    SideEffects = string.Empty, // 暂时为空，可以后续添加
                    Status = medicine.IsDeleted ? 0 : 1, // 使用IsDeleted作为状态
                    CreateTime = medicine.CreateTime,
                }).ToList();

                result.Data = resultList;
                result.Code = APIEnums.Success;
                result.Msg = $"搜索成功，共找到{resultList.Count}条记录";

                _logger.LogInformation($"药物智能搜索成功，共找到{resultList.Count}条记录");
            }
            catch (Exception ex)
            {
                result.Code = APIEnums.Fail;
                result.Msg = "药物搜索失败";
                _logger.LogError(ex, "药物智能搜索时发生异常");
            }

            return result;
        }
    }
} 